var contextPath = $("#contextPath").val();
var orderInfo = $("#orderInfo");
var goodsId = $("#goodsId").val();
var addressId = $("#addressId");
var goodsListV = $("#goodsList");
var totalPriceShow = $("#totalPriceShow");
var transitShow = $("#transitShow");
var allPointsShow = $("#allPointsShow");
var balanceShow = $("#balanceShow");
var cashBackShow = $("#cashBackShow");
var payModeShow = $("#payModeShow");
var type =$("#type");
var spec=$("#spec").val();
var buyNum=$("#buyNum").val();
var payPwd,params,isWx,ratioConfigure,terminal;
var payPwd,params,isWx,ratioConfigure,terminal;
var load = layer.open({type: 2,shadeClose:false});
var selectPoints=0,selectPointsPrice = 0,totalPrice = 0,realTotalPrice = 0,transit = 0,user,selectId=0,isExistsPoints=0,sPointsInt=0,showPointsInt=0,selectShowPoints=0;
var level = 0, curPrice = 0;
form.Radio('.data_radio', {
    onchange: function(radios, _this) {
    	var val = _this.querySelector('a').getAttribute('payMode');
    	$("#payMode").val(val);
    	
    }
  });
$(function() {
	isWx = isWeiXin();
	terminal = $('#terminal').val();
	dataInit(type.val());
	function dataInit(type){
		var url,data;
		if(type == 'buy_now'){
			url = contextPath+"/pay/getBuyNowGoodsInfo";
			data = {goodsId:goodsId,addressId:addressId.val(),buyNum:$("#buyNum").val(),spec:$("#spec").val()}
		}else{
			url = contextPath+"/pay/getShopCartgInfo";
			data = {goodsId:goodsId,addressId:addressId.val()};
		}
		$.ajax({
			url:url,
			type:"post",
			async:true,
			data:data,
			dataType:"json",
			success : function(data, textStatus) {
				var state = data.result.state;
				if(state == 1){
				//默认收货地址
				var dAddressList = data.dAddressList;
				if(dAddressList.length > 0){
					var dAddressObj = dAddressList[0];
					$("#orderInfo").prepend('<div class="floor" id="addressCheck"><div class="order_item_top"><p class="item_top_title">收货信息</p></div><div class="address poi" id="dAddress"><div class="address_select"><p class="address_info"><span class="name">'+dAddressObj.receiverName+'&nbsp;&nbsp;&nbsp;&nbsp;'+dAddressObj.receiverPhone+'</span></p><p class="address_info"><i class="icon_address_01 dib vm"></i><span class="address_info_txt">'+dAddressObj.receiverAddress+'</span> </p></div><i class="icon_order_nav"></i></div><p class="address_img_bb"></p></div>');
					
//					$("#dAddress").find(".name").text(dAddressObj.receiverName);
//					$("#dAddress").find(".phone").text(dAddressObj.receiverPhone);
//					$("#dAddress").find(".address_info_txt").text(dAddressObj.receiverAddress);
					addressId.val(dAddressObj.id);
				}else{
					$("#orderInfo").prepend(' <div class="floor" id="addressCheck"><div class="order_item_top"><p class="item_top_title">收货信息</p></div><div class="address_default"><a href="javascript:addR();"><div class="tips_address_add"><em class="dib vm n">+</em><span class="dib vm">添加收货地址</span></div></a></div><p class="address_img_bb"></p></div>');   
				}
				//商品列表
				var goodsList = data.goodsList;
				user = data.user;
				level = parseInt(user.level);
				allPointsShow.find('.order_summary_bd p').html('最高可使用'+user.points+'兑换券');
				balanceShow.find('.order_summary_bd p').html('当前余额'+user.balance);
				if(goodsList.length > 0){
					var html='<form id="toPayform" method="post">';
					transit=data.transit;
					$.each(goodsList,function(i,v){
						var bidPrice = v.bidPrice;
						var price = ((v.isSales == '01')?v.realPrice:v.price);
						var marketPrice = v.marketPrice;
						var changePoints = v.changePoints;
						var changePrice = v.changePrice;
						var returnAmount = v.returnAmount;
						var changeShowPoints = v.changePoints;
						if(v.isSelectSpec == "01"){
							ratioConfigure = data.ratioConfigure;
							changePoints = getReqPoints(bidPrice,marketPrice,price);
							changeShowPoints = getShowReqPoints(bidPrice,marketPrice,price);
							changePrice = toDecimal(price-changePoints);
						}
						if(v.isPointsBuy == '01'){
							realTotalPrice +=  changePrice * v.buyNum;
							totalPrice += (changePrice+changeShowPoints) * v.buyNum;
							if(changePrice == 0){
								html+='<div class="order_goods_item"><div class="goods_img"><i class="vip_mark"></i><img src="'+v.thumb+'"></div><div class="goods_info"><div class="order_goods_info"><div class="goods_info_name">'+v.title+'</div><div class="goods_info_price tr"><p class="rebate"> <em class="n">'+changeShowPoints+'</em> 兑换券</p></div></div><div class="order_goods_info">';
							}else{
								html+='<div class="order_goods_item"><div class="goods_img"><i class="vip_mark"></i><img src="'+v.thumb+'"></div><div class="goods_info"><div class="order_goods_info"><div class="goods_info_name">'+v.title+'</div><div class="goods_info_price tr"><p class="rebate"> <em class="n">'+changeShowPoints+'</em> 兑换券</p><p class="rebate">+ <span>'+changePrice+'</span>元</p></div></div><div class="order_goods_info">';
							}							
						}else{
							realTotalPrice += price * v.buyNum;
							totalPrice += price * v.buyNum;
							html+='<div class="order_goods_item"><div class="goods_img"><img src="'+v.thumb+'"></div><div class="goods_info"><div class="order_goods_info"><div class="goods_info_name">'+v.title+'</div><div class="goods_info_price tr"><p class="normal">&yen;'+price+'</p>';
							if(v.returnPoints>0){
								html+='<p class="commodity__live_voucher">赠 <em class="n">'+v.returnPoints+'</em>兑换券</p></div></div><div class="order_goods_info">';
							}else{
								html+='</div></div><div class="order_goods_info">';
							}				
						}
						var goodsSpecPro = v.params.goodsSpecPro;
						if(goodsSpecPro != null && goodsSpecPro.length > 0){
							$.each(goodsSpecPro,function(specI,specV){
								html+='<p class="goods_info_color">'+specV.labelName+'：'+specV.attrName+'&nbsp;&nbsp;</p>';
							});
						}
						
						html+='<p class="goods_info_quantity"> X'+v.buyNum+'</p>';
						var ispointsBuy = ' style=\"display: none\"';
						if(v.isPointsBuy == '01'){
							isExistsPoints = 1;
							//if(changePoints <= user.points && changePoints > selectPoints){
								selectPoints += changePoints * v.buyNum;
								selectShowPoints += changeShowPoints * v.buyNum;
								selectPointsPrice += changeShowPoints * v.buyNum;
								selectId = v.id;
							//}
						}
						
						html+='<p class="integral_operating" '+ispointsBuy+'><a id="a'+v.id+'" isVipFullback='+v.isVipFullback+' class="btn_integral_01 btn_integral_01_no" href="javascript:;">';
						html+='兑换券兑换<input type="hidden" name="isPointsBuys" value="0"><input type="hidden" name="price" value="'+price+'"><input type="hidden" name="pointsNum" value="'+changePoints+'"><input type="hidden" name="cashBackPrice" value="'+returnAmount+'"></a></p>';
						html+='</div></div></div>';
						
						html+='<input type="hidden" name="goodsIds" value="'+v.id+'">';
						html+='<input type="hidden" name="bidPrice" value="'+v.bidPrice+'">';
						html+='<input type="hidden" name="curPrice" value="'+v.realPrice+'">';
						html+='<input type="hidden" name="buyNums" value="'+v.buyNum+'">';
						html+='<input type="hidden" name="specs" value="'+toReplace(v.spec)+'">';
					});
					html+='<input type="hidden" id="payMode" name="payMode" value="00">';
					html+='<input type="hidden" id="totalPointsNum" name="totalPointsNum" value="0">';
					html+='<input type="hidden" id="totalShowPointsNum" name="totalShowPointsNum" value="0">';
					html+='<input type="hidden" id="totalPointsPrice" name="totalPointsPrice" value="0">';
					html+='<input type="hidden" id="balancePrice" name="balancePrice" value="0">';
					html+='<input type="hidden" id="addPrice" name="addPrice" value="0">';
					html+='<input type="hidden" id="totalPrice" name="totalPrice" value="0">';
					html+='<input type="hidden" id="realTotalPrice" name="realTotalPrice" value="0">';
					html+='<input type="hidden" id="totalCashBackPrice" name="totalCashBackPrice" value="0">';
					html+='</form>'
					totalPrice = totalPrice + transit
					realTotalPrice = realTotalPrice + transit;
					goodsListV.append(html);
					if(selectId != 0){
						$("#a"+selectId).removeClass("btn_integral_01_no");
						$("#a"+selectId).find('input[name=isPointsBuys]').val('1');
					}
					totalPriceShow.html('&yen;'+toDecimal(realTotalPrice));
					transitShow.html('&yen;'+toDecimal(transit));
					
					$("#totalPrice").val(toDecimal(totalPrice));
					$("#realTotalPrice").val(toDecimal(realTotalPrice));
					$("#transit").val(toDecimal(transit));
					priceInit(true,true);
					orderInfo.show();
					setTimeout(function(){layer.close(load);},50);
				}	
				}else{
					layer.open({
					    title: '提示',
					    content: data.result.message,
					    btn: ['我知道了'],
					    yes: function(index){
					    	layer.close(load);
							location.href=contextPath+'/';
					    }
					});
					
				}
				
				
				
				
			},
			error : function(XMLHttpRequest, textStatus, errorThrown){
				layer.open({
				    title: '提示',
				    content: '网络异常！',
				    btn: ['我知道了'],
				    yes: function(index){
				    	layer.close(load);
						location.href=contextPath+'/';
				    }
				});	
			}
		});	
		
	}
	
	
$(document).on("click",".btn_integral_01",function(){
	if($(this).hasClass('btn_integral_01_no')){
		var tempPoints = selectPoints + parseInt($(this).find('input[name=pointsNum]').val());
		var tempPointsPrice = selectPointsPrice + toDecimal($(this).find('input[name=price]').val());
		if(tempPoints<=user.points){
			selectPoints =tempPoints;
			selectPointsPrice = tempPointsPrice;
			$(this).removeClass('btn_integral_01_no');	
			$(this).find('input[name=isPointsBuys]').val('1');
			$("#allPointsCheck").addClass('simulation_checkbox_active');
			priceInit($("#allPointsCheck").hasClass('simulation_checkbox_active'),$("#balanceCheck").hasClass('simulation_checkbox_active'));
		}else{
			layer.open({
			    content: '兑换券不够！',
			    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
			    time: 1,
			    shade: false
			});	
		}
		
	}else{
		selectPoints = selectPoints - parseInt($(this).find('input[name=pointsNum]').val());
		selectPointsPrice = selectPointsPrice - toDecimal($(this).find('input[name=price]').val());
		$(this).addClass('btn_integral_01_no');	
		$(this).find('input[name=isPointsBuys]').val('0');
		priceInit($("#allPointsCheck").hasClass('simulation_checkbox_active'),$("#balanceCheck").hasClass('simulation_checkbox_active'));
	}
	
	
});


function priceInit(isPoints,isBalance){
	//初始化参数
	$("#payMode").val("00");
	$("#totalPointsNum").val(0);
	$("#totalPointsPrice").val(0);
	$("#balancePrice").val(0);
	$("#addPrice").val(0);
	allPointsShow.find('.order_summary_ft').html('');
	allPointsShow.find('.simulation_checkbox').removeClass('simulation_checkbox_active');
	balanceShow.find('.order_summary_ft').html('');
	balanceShow.find('.simulation_checkbox').removeClass('simulation_checkbox_active');
	$("#addPriceShow").find('.order_summary_ft em').html('&yen;0');
	cashBackShow.hide();
	payModeShow.hide();
	curPrice = realTotalPrice;
	if(isPoints){
	sPointsInt = parseInt(selectPoints);
	showPointsInt = parseInt(selectShowPoints);
	var sPointsPrice = toDecimal(selectPointsPrice);
	if(sPointsInt>0){
		if(user.points >= sPointsInt){
			allPointsShow.find('.order_summary_bd p').html('最高可使用:'+user.points+'兑换券，' + '消费兑换券为:'+showPointsInt+'兑换券');
			$("#allPointsCheck").addClass('simulation_checkbox_active');
		}else{
			allPointsShow.find('.order_summary_bd p').html('最高可使用:'+user.points+'兑换券，' + '消费兑换券为:'+showPointsInt+'兑换券，兑换券不足');
			$("#addPriceShow").find('.order_summary_ft em').html('&yen;'+toDecimal(curPrice));
			$("#balancePrice").val(toDecimal(curPrice));
			isBalance = false;
			curPrice = 0;
		}
		$("#totalPointsNum").val(showPointsInt);
		$("#totalShowPointsNum").val(showPointsInt);
		$("#totalPointsPrice").val(sPointsPrice);
		$("#payMode").val("JF");
	}
	}
	if(isBalance){
	if(curPrice>0){
		//var balancePrice = (user.balance < curPrice)?user.balance:curPrice;
		if(curPrice <= user.balance){
			balanceShow.find('.order_summary_ft').html('-'+toDecimal(curPrice));
			$("#balancePrice").val(toDecimal(curPrice));
			$("#payMode").val("YE");
			balanceShow.find('.simulation_checkbox').addClass('simulation_checkbox_active');
			curPrice = 0;
		}
	}
	}
	if(curPrice>0){
		$("#addPriceShow").find('.order_summary_ft em').html('&yen;'+toDecimal(curPrice));
		$("#addPrice").val(toDecimal(curPrice));
		var payMode = $("#payModeShow").find('.simulation_checkbox_active').attr('payMode');
		$("#payMode").val(payMode);
		payModeShow.show();
	}
	
}

$("#balanceShow").on('click',function(){
	if($("#balanceCheck").hasClass('simulation_checkbox_active')){
		$("#balanceCheck").removeClass('simulation_checkbox_active');
	}else{
		if(transit ==0 && transit == curPrice){
			layer.open({
			    content: '该商品只能兑换券换购！',
			    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
			    time: 1,
			    shade: false
			});
			return;
		}
		if(user.balance < curPrice){
			layer.open({
			    content: '余额不足！',
			    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
			    time: 1,
			    shade: false
			});
			return;
		}
		if(user.points >= sPointsInt){
			$("#balanceCheck").addClass('simulation_checkbox_active');
		}else{
			layer.open({
			    content: '兑换券不足不能余额支付！',
			    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
			    time: 1,
			    shade: false
			});
			return;
		}
		
		
	}
	if(sPointsInt > 0){
		$("#allPointsCheck").addClass('simulation_checkbox_active');
	}
	priceInit($("#allPointsCheck").hasClass('simulation_checkbox_active'),$("#balanceCheck").hasClass('simulation_checkbox_active'));
	
});

function toDecimal(x) {    
    var f = parseFloat(x);    
    if (isNaN(f)) {    
        return;    
    }    
    f = Math.round(x*100)/100;    
    return f;    
}    

function toReplace(obj){
	if(obj !='' || obj != null){
		return obj.replace(new RegExp(/(,)/g),'#');
	}
	console.log(obj);
	return obj;
}

$(document).on('click','#dAddress',function(){
	var type = $("#type").val();
	/*if(type == 'buy_now'){*/
	$("#addressForm").attr("action",contextPath+"/address/buyNow").submit();
	//}
});


$("#goPay").on('click',function(){
	var payMode = $("#payMode").val();
	var totalPointsNum = $("#totalPointsNum").val();
	var totalPointsPrice = $("#totalPointsPrice").val();
	var balancePrice = $("#balancePrice").val();
	var addPrice = $("#addPrice").val();
	var totalPrice = $("#totalPrice").val();
	var realTotalPrice = $("#realTotalPrice").val();
	var transit = $("#transit").val();
	var addressId = $("#addressId").val();
	if(addressId == ''){
		layer.open({
		    title: '提示',
		    content: '请选择收货地址',
		    btn: ['我知道了']
		});	
		return;
	}
	
	if(parseFloat(totalPrice) <=0){
		layer.open({
		    title: '提示',
		    content: '支付金额不能小于零',
		    btn: ['我知道了']
		});	
		return;
	}
	
	var ntotalPrice = parseFloat(balancePrice) + parseFloat(addPrice) + parseFloat(totalPointsPrice);

	if(toDecimal(totalPrice) != toDecimal(ntotalPrice)){
		layer.open({
		    title: '提示',
		    content: '支付金额有误',
		    btn: ['我知道了']
		});	
		return;
	}
	
	if(payMode == '00'){
		layer.open({
		    title: '提示',
		    content: '请选择支付方式',
		    btn: ['我知道了']
		});	
		return;
	}
	load = layer.open({type: 2,shadeClose:false});
	
	//封装参数
	params = $("#toPayform").serializeArray();
	params.push({"name":"type","value":$("#type").val()});
	params.push({"name":"addressId","value":addressId});
	params.push({"name":"tag","value":"WAP"});
	params.push({"name":"line","value":"00"});
	params.push({"name":"descountTotalPrice","value":realTotalPrice});
	
	
	isPay = true;
	if(payMode == 'JF' || payMode == 'YE'){
		
		//验证支付密码并支付
		zhifuTips();
	
	}else if(payMode == 'WX'){
		//微信支付
		if(isWx){
			goWxJsPay();
		}else if(terminal == "app"){
			goWxAppPay();
		}else{
			layer.open({
			    title: '提示',
			    content:'请在使用微信打开商城',
			    btn: ['我知道了']
			});	
			layer.close(load);
			return;
		}	
	}else if(payMode == 'ZFB'){
		//支付宝支付
		goAliPayWap();
	}

});

function goAliPayWap(){
	$.ajax({
		url:contextPath+"/pay/confirm_alipay_pay",
		type:"post",
		async:true,
		data:params,
		dataType:"json",
		success : function(data, textStatus) {
			var state = data.result.state;
			console.log(data);
			if(state == 1){
				var url = data.url;
				$('#alipay_box').append(url);
			}else{
				layer.close(load);
				layer.open({
				    title: '提示',
				    content: data.result.message,
				    btn: ['我知道了']
				});
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			layer.open({
			    content:textStatus,
			    time: 2
			});
		}
	});	
}

function goWxJsPay(){
	$.ajax({
		url:contextPath+"/pay/confirm_wxjs_pay",
		type:"post",
		async:true,
		data:params,
		dataType:"json",
		success : function(data, textStatus) {
			var state = data.result.state;
			if(state == 1){
				doWxJsPay(data.prePayInfo,data.payCode);
			}else{
				layer.open({
				    title: '提示',
				    content: data.result.message,
				    btn: ['我知道了']
				});
			}
			layer.close(load);
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			layer.open({
			    content:textStatus,
			    time: 2
			});
		}
	});	
}

function goWxAppPay(){
	$.ajax({
		url:contextPath+"/pay/confirm_app_pay",
		type:"post",
		async:true,
		data:params,
		dataType:"json",
		success : function(data, textStatus) {
			var state = data.result.state;
			if(state == 1){
				var params = JSON.stringify(data.prePayInfo);
				window.location.href = "wechat://"+params;
			}else{
				layer.open({
				    title: '提示',
				    content: data.result.message,
				    btn: ['我知道了']
				});
			}
			layer.close(load);
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			layer.open({
			    content:textStatus,
			    time: 2
			});
		}
	});	
}

function doWxJsPay(prePayInfo, code){
	if (typeof WeixinJSBridge == "undefined"){
		   if( document.addEventListener ){
		       document.addEventListener('WeixinJSBridgeReady', function(){
		    	   onBridgeReady(prePayInfo, code);
		       }, false);
		   }else if (document.attachEvent){
		       document.attachEvent('WeixinJSBridgeReady', function(){
		    	   onBridgeReady(prePayInfo, code);
		       }); 
		       document.attachEvent('onWeixinJSBridgeReady', function(){
		    	   onBridgeReady(prePayInfo, code);
		       });
		   }
		}else{
		   onBridgeReady(prePayInfo, code);
		}
}
function onBridgeReady(prePayInfo, code){
	WeixinJSBridge.invoke('getBrandWCPayRequest',prePayInfo,
		    function(res){
		       //支付成功或失败前台判断
    	       if(res.err_msg=='get_brand_wcpay_request:ok'){
    	    	   layer.open({
					    title: '提示',
					    content: '恭喜你，支付成功！',
					    btn: ['我知道了'],
					    yes: function(index){
					        layer.close(index);
					        location.href=contextPath+"/pay/payOneResult?code="+code;
					    }
					});	
    	       }else if(res.err_msg=='get_brand_wcpay_request:cancel'){	   
    	    	   //deleteOrder(pi);
    	    	   layer.open({
					    title: '提示',
					    content: '支付已取消！',
					    btn: ['我知道了']
					});	
    	       }else{
    	    	   //deleteOrder(pi);
    	    	   layer.open({
					    title: '提示',
					    content: '支付失败，请重试！',
					    btn: ['我知道了']
					});	
    	       }
		     });
	
}


function confirmBalancePay(params){
	$.ajax({
		url:contextPath+"/pay/confirm_balance_pay",
		type:"post",
		async:true,
		data : params,
		dataType:"json",
		error : function(req, textStatus, errorThrown) {
			layer.open({
			    title: '提示',
			    content: '支付失败，请重试',
			    btn: ['我知道了']
			});		
			
		},
		success : function(data, textStatus) {
			layer.close(load);
			var state = data.result.state;
			if(state == 1){
				var code = data.payCode;
				var le = $(document).find(".orderInfo").length;
				if (le == 1) {
					$(document).on("click",function(){
						location.href=contextPath+"/pay/payOneResult?code="+code;
					})
				}
				layer.open({
				    content: '支付成功！',
				    btn: ['我知道了'],
				    yes: function(index){
				    	location.href=contextPath+"/pay/payOneResult?code="+code;
				    }
				});	
			}else{
				var message = data.result.message;
				var url = data.result.url;
				layer.open({
				    title: '提示',
				    content: message,
				    btn: ['我知道了'],
				    yes: function(index){
				    	layer.close(index);
				        if(url != null){
							location.href=contextPath+url;
						}
				    }
				});	
			}
		}
	});
}





function zhifuTips() {
	$.ajax({
		url:contextPath+"/user/getPayPwd",
		type:"post",
		async:true,
		dataType:"json",
		success : function(data, textStatus) {
			layer.close(load);
			var state = data.result.state; 
			if(state == 1){
				payPwd = data.payPwd;
				if(payPwd == '' || payPwd == null){
			    layer.open({
			      content: '<div class="zhifuTips"><h1>您还没有设置支付密码</h1><p>为保障您的支付安全，请您设置支付密码！</p></div>',
			      btn: ['去设置', '其他支付方式'],
			      yes: function(index) {
			        layer.close(index);
			        zhifuSet();
			      }
			    });
				}else{
					zhifuPlay();
				}
				
			}else{
				var message = data.result.message;
				layer.open({
				    title: '提示',
				    content: message,
				    btn: ['我知道了'],
				    yes: function(index){
				    	layer.close(index);
				    }
				});	
			}
		}
	});

    
  }
  //=================== 设置支付密码 ===================
  function zhifuSet() {
    layer.open({
      type: 1,
      content: '<div class="set_zhifu"><div class="zhifu_pswd"><p class="tc"> 请输入支付密码</p><div class="zhifu_pswd_form rel" id="impPayPwd"><div class="form"><input type="password" maxlength="6" name="" value=""></div><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"></div></div><div class="ui_cells"><div class="ui_cell login_submit"><div class="ui_cell_bd"><a class="ui_btn ui_btn_primary btn_login_submit db tc" href="javascript:;">下一步</a></div></div></div></div><div class="change_zhifu dn"><div class="zhifu_pswd"><p class="tc"> 请再次输入支付密码</p><div class="zhifu_pswd_form rel" id="impPayPwdT"><div class="form"><input type="password" maxlength="6" name="" value=""></div><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"></div></div><div class="ui_cells"><div class="ui_cell login_submit"><div class="ui_cell_bd"><a class="ui_btn ui_btn_primary btn_login_submit db tc" href="javascript:;">完成</a></div></div></div></div>',
      anim: 0,
      style: 'position:fixed; bottom:0; left:0; width:100%; height:100%;border:none; box-sizing: border-box;',
      success: function() {
    	  var set = document.querySelector('.set_zhifu'),
          change = document.querySelector('.change_zhifu'),
          setBtn = set.querySelector('.btn_login_submit'),
          changeBtn = change.querySelector('.btn_login_submit');
    	  
          var ele = $(".zhifu_pswd_form");
          ele.each(function(index,el){
          	 zhifu(el);
          })
    	var impPayPwd,impPayPwdT; 
        setBtn.addEventListener('click', function() {
        	impPayPwd = verifyPwd($("#impPayPwd"));
        	if(impPayPwd.length == 6){
        		set.style.display = "none";
                change.style.display = "block";
        	}
          
        }, false);
        // 完成设置
      changeBtn.addEventListener('click', function() {
    	  impPayPwdT = verifyPwd($("#impPayPwdT"));
      	if(impPayPwdT.length == 6){
      		if(impPayPwd != impPayPwdT){
      		isPay = false;
      		layer.open({
			    content: '两次密码输入不一致！',
			    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
			    time: 1,
			    shade: false
			});
      		}else{
      			//修改支付密码并支付
      			savePayPwd(impPayPwd);
      		}

      	}
        
      }, false);
 
      }
    });
  }
  //修改支付密码并支付
  function savePayPwd(impPayPwd){
	  $.ajax({
			url:contextPath+"/user/updatePayPwd",
			type:"post",
			async:true,
			data:{pwd:impPayPwd},
			dataType:"json",
			success : function(data, textStatus) {
				var state = data.result.state; 
				if(state == 1){
					//去支付
        			confirmBalancePay(params);
				}else{
					var message = data.result.message;
					layer.open({
					    title: '提示',
					    content: message,
					    btn: ['我知道了'],
					    yes: function(index){
					    	layer.close(index);
					    }
					});	
				}
			}
		});
  }
  
  //=================== 支付密码 ===================
  function zhifuPlay(callback) {
    layer.open({
      type: 1,
      content: '<div class="zhifuPlay"><div class="zhifu_pswd"><p class="tc">&nbsp;请输入支付密码</p><div class="zhifu_pswd_form rel" id="impPayPwd"><div class="form"><input type="password" maxlength="6" name="" value=""></div><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password"><input class="item" type="password">			</div></div><div class="ui_cells"><div class="ui_cell login_submit"><div class="ui_cell_bd"><a class="ui_btn ui_btn_primary btn_login_submit db tc" href="javascript:;">支付</a></div></div></div><p class="zhifuPswdTips tr"><a href="'+contextPath+'/user/toCheckPhone">忘记密码？</a></p></div>',
      anim: 0,
      style: 'position:fixed; bottom:0; left:0; width:100%; height:100%;border:none; box-sizing: border-box;',
      success: function() {
	      var ele = $(".zhifu_pswd_form");
	      zhifu(ele.get(0));
	      var set = document.querySelector('.zhifuPlay'),
          setBtn = set.querySelector('.btn_login_submit');
	      
	      setBtn.addEventListener('click', function() {
	    	  var impPayPwd = verifyPwd($("#impPayPwd"));
	        	if(impPayPwd.length == 6){
	        		if(hex_md5(impPayPwd) != payPwd){
	              		layer.open({
	        			    content: '密码输入不正确！',
	        			    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
	        			    time: 1,
	        			    shade: false
	        			});
	        		}else{
	        			//去支付
	        			confirmBalancePay(params);
		        	}
	        	}
	          
	        }, false);
	      
      }
    });
  }

});
//验证表单字符长度
function verifyPwd(element){
	var divs = element.find('div');
	var inputs = divs.find('input');
	var impPayPwd = '';
	var val = $.trim(inputs.val());
	if(val==''){
		layer.open({
		    content: '请输入支付密码！',
		    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
		    time: 1,
		    shade: false
		});
		return false;
	}
	impPayPwd+=val;
	return impPayPwd;
}
//支付密码效果
function zhifu(element) {
	  var input = element.querySelector('input'),
      divs = element.querySelectorAll('.item');
    input.addEventListener('focus', function() {
      var l = this.value.length - 1;
      l = l < 0 ? 0 : l;
      divs[l].classList.add('focuer');
    }, false);
    input.addEventListener('blur', function() {
      [].forEach.call(divs, function(el) {
        el.classList.remove('focuer');
      });
    }, false);
    input.addEventListener('input', function() {
      var value = this.value,
        l = value.length;
      for (var i = 0; i < Math.max(6, l); i++) {
        divs[i].value = value[i] || '';
        divs[i].classList.remove('focuer');
      }
      if (l > 0) {
        divs[Math.min(5, l)].classList.add('focuer');
      } else {
        divs[0].classList.add('focuer');
      }
    }, false);
	
//	  var divs = element.find('div');
//    var inputs = divs.find('input');
//    var length = divs.length;
//    var index = 0;
//    inputs.hide();
//    // 点击判断开始位置
//    divs.on('click', function() {
//      inputs.each(function(i, input) {
//        var dn = $(input).css('display'),
//          val = this.value.trim(),
//          valr = '';
//        if (dn === 'none') {
//          if (index >= length) {
//            index = i;
//          }
//        } else {
//          index = i;
//        }
//        inputIndex(index);
//      });
//    });
//    // 输入自动跳转到下一个
//    inputs.on('keydown', function(ev) {
//      var val = this.value.trim(),
//        num = $(this).parent().index();
//      if (ev.which !== 8) {
//        if (val !== '') {
//          num += 1;
//        }
//        $(this).parent().next().find('input').show();
//        inputIndex(num);
//      } else {
//        if (val == '') {
//          num -= 1;
//          $(this).hide();
//        }
//        if (num < 0) {
//          num = 0;
//        }
//        inputIndex(num);
//
//      }
//    });
//
//    function inputIndex(i) {
//      if (i >= length) {
//        inputs.eq(length - 1).trigger('blur');
//      } else {
//        inputs.eq(i).show().trigger('focus');
//      }
//    };
}

function isWeiXin(){ 
	var ua = window.navigator.userAgent.toLowerCase(); 
	if(ua.match(/MicroMessenger/i) == 'micromessenger'){ 
	return true; 
	}else{ 
	return false; 
	} 
}

function isAndroid(){
	var ua = window.navigator.userAgent.toLowerCase(); 
	if(ua.match(/android/i) == "android"){ 
	return true; 
	}else{ 
	return false; 
	} 
}

function isIphone(){ 
	var ua = window.navigator.userAgent.toLowerCase(); 
	if(ua.match(/iphone os/i) == "iphone os"){ 
	return true; 
	}else{ 
	return false; 
	} 
}

function getReqPoints(bidPrice, marketPrice, price){
	var changePoints = 0;
	var discount = toDecimal3(bidPrice/marketPrice);
	var minRatio = ratioConfigure.minRatio;
	var maxRatio = ratioConfigure.maxRatio;
	if(discount<=minRatio){
		changePoints = price;
	}else if(discount<=maxRatio){
		changePoints = parseInt(price*(1-discount/10)/(1-minRatio/10));
	}
	return changePoints;
}

function getShowReqPoints(bidPrice, marketPrice, price){
	var changePoints = 0;
	var discount = toDecimal3(bidPrice/marketPrice);
	var minRatio = ratioConfigure.minRatio;
	var maxRatio = ratioConfigure.maxRatio;
	if(discount<=minRatio){
		changePoints = Math.ceil(price);
	}else if(discount<=maxRatio){
		changePoints = parseInt(price*(1-discount/10)/(1-minRatio/10));
	}
	return changePoints;
}
function addR(){
	$("#addressForm").attr("action",contextPath+"/address/buyNow").submit();
}

function toDecimal3(x) {    
    var f = parseFloat(x);    
    if (isNaN(f)) {    
        return;    
    }    
    f = Math.round(x*1000)/100;    
    return f;    
} 
